<html>
	<head>
		<link rel="stylesheet" type="text/css" href="css/interfaceList.css" />
		<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
		<link rel="stylesheet" type="text/css" href="css/glyphicons.css" />
		<link rel="stylesheet" type="text/css" href="css/glyphicons-halflings.css" />
		<link rel="stylesheet" type="text/css" href="css/jquery.mCustomScrollbar.min.css" />
		<link rel="stylesheet" type="text/css" href="css/pnotify.custom.min.css" />
		<link rel="stylesheet" href="css/ui-dialog.css">


		<script type="text/javascript" src="js/jquery.js"></script>
		<script type="text/javascript" src="js/jquery-ui-1.10.4.min.js"></script>
		<script type="text/javascript" src="js/jquery.mCustomScrollbar.min.js"></script>
		<script type="text/javascript" src="js/jquery.mousewheel.min.js"></script>
		<script type="text/javascript" src="js/dialog-plus-min.js"></script>
		<script type="text/javascript" src="js/pnotify.custom.min.js"></script>
		<script type="text/javascript" src="js/jsviews.js"></script>
		<script type="text/javascript" src="js/utils.js"></script>

	</head>
	<body>
		<div class="interfaceListBox">
			<div class="rootMenuBox">
				<div class="rootMenuLoadingBox">
					<img src="./image/loading.gif" />
	        		<p>根菜单获取中...</p>
				</div>
				<div class="rootMenuHeadBox">
					
				</div>
				<ul class="rootMenuUl" style="overflow:auto;">
					<script  id="rootMenuTemp" type="text/x-jsrender">
						{{for result}}
							<li title="{{:name}}" id="{{:id}}"><span class="glyphicons glyphicons-pushpin listIconSpan"></span>{{:name}}<span class="halflings halflings-chevron-right selectedSpan"></span></li>
						{{/for}}
					</script>
				</ul>
			</div>
			<div class="listMenuBox">
				<div class="defaultContent">
					<span class="glyphicons glyphicons-book-open"></span>
					<p>你还未选择需要查看的根菜单</p>
				</div>
				<div class="loadingContent" id="loadingContent">
			        <img src="./image/loading.gif" />
			        <p>接口列表获取中...</p>
			    </div>
				<div class="listMenuHeadBox"></div>
				<table class="myTable">
					<thead>
      					<tr>
      						<td class="nameSearch">接口名称 <span class="glyphicons glyphicons-search"></span></td>
      						<td>接口地址</td>
      						<td>接口说明</td>
      						<td>请求类型</td>
      						<td>所需权限</td>
      						<td>RESTFUL</td>
      						<td>BODY</td>
      						<td>返回结果</td>
      						<td>操作</td>
      					</tr>
      				</thead>
      				<tbody id="tbodybox">
      					<script id="sonMenuListTemp" type="text/x-jsrender">
      					{^{for result}}
      					<tr id="{{:id}}" name="{{:menu_id}}">
      						<td data-title="接口名称" data-field="name" data-link="value{:name}" class='editTd inputEdit'>{^{:name}}<span class="glyphicons glyphicons-pencil"></span></td>
      						<td data-title="接口地址" data-field="path" data-link="value{:path}" class='editTd inputEdit'>{^{:path}}<span class="glyphicons glyphicons-pencil"></span></td>
      						<td data-title="接口说明" data-field="description" data-link="value{:description}" class='editTd inputEdit'>...<span class="glyphicons glyphicons-pencil"></span></td>
      						<td data-title="请求类型" data-link="value{:method}" data-field="method" class='editTd radioEdit'>{^{:method}}<span class="glyphicons glyphicons-pencil"></span></td>
      						<td data-title="所需权限" class='editTd permissionEdit'>无<span class="glyphicons glyphicons-lock"></span></td>
      						<td data-title="RESTFUL参数" data-field="RESTFUL" class='editTd paramsEdit'>{{:restfulCount}}个<span class="glyphicons glyphicons-file"></span></td>
      						<td data-title="BODY参数" data-field="BODY" class='editTd paramsEdit'>{{:bodyCount}}个<span class="glyphicons glyphicons-file-lock"></span></td>
      						<td data-title="返回结果" data-field="result" data-link="value{:result}" class='editTd resutlEdit'>...<span class="glyphicons glyphicons-article"></span></td>
      						<td class='actionTd'>
      							<span class="glyphicons glyphicons-bin removeInterface"></span>
      						</td>
      					</tr>
      					{{/for}}
      					</script>
      				</tbody>
				</table>
			</div>
		</div>
	</body>
	<script>
	$(window).load(function(){
      $(".rootMenuUl").mCustomScrollbar({theme:"rounded"});
      
    });

    $(function(){

    	//根菜单数据
      	var rootMenuData = {};

      	//子菜单列表数据
      	var sonMenuListData = {};

      	//获取根菜单模版
      	var rootMenuTemp = $.templates("#rootMenuTemp");

      	//获取子菜单列表模版
      	var sonMenuListTemp = $.templates("#sonMenuListTemp");

        //是否提交中
        var isSubmit = true;

      	

		//获取菜单信息
      	getRootMenuData();

      	//根菜单点击效果
      	rootMenuClickEvent();


      	//获取根菜单
      	function getRootMenuData(){
      		//加载根菜单
	        $.getJSON("./handler/getRootMenu.php",function(data){
	            
	            //判断是否返回错误
	            if(!data.success){
	               notifyShow('error', data.message);
	               return;
	            }

	            rootMenuData = {result : data.result};

	            
	            //为模板绑定数据
	            rootMenuTemp.link(".rootMenuUl",rootMenuData);

	            //关闭根菜单加在效果
	            rootMenuLoadingEnd();
            	
	            
	        });
      	}

      	//根菜单点击效果
      	function rootMenuClickEvent(){

      		$(document).on("click",".rootMenuUl li",function(){

      			//获取菜单id
      			var rootMenuId = $(this).attr("id");


      			//选中效果
      			$(".rootMenuUl li .selectedSpan").hide();
      			$(".rootMenuUl li").removeClass("selected");

      			$(this).find(".selectedSpan").show();
      			$(this).addClass("selected");

      			//隐藏默认显示，并开始加载
      			hideDefaultContent();
      			sonMenuListLoadingStart();

      			//获取子接口列表
      			getSonMenuListData(rootMenuId);


      		});

      	}

      	//获取子接口列表数据
      	function getSonMenuListData(rootMenuId){

      		//加载根菜单
	        $.getJSON("./handler/getSonMenuDetail.php?rootMenuId="+rootMenuId,function(data){
	            
	            //判断是否返回错误
	            if(!data.success){
	               notifyShow('error', data.message);
	               return;
	            }

	            sonMenuListData = {result : data.result};

              console.log(sonMenuListData);

	            sonMenuListTemp.link("#tbodybox",sonMenuListData);

              $(".listMenuBox").css("overflow","auto");

	            sonMenuListLoadingEnd();
   
	        });




      	}

        //更新接口信息操作
        function updateInterfactDetail(params,fn){

          $.post("./handler/updateInterfaceDetail.php",params,function(data){

              //打开提交开关
              isSubmit = true;

              //判断是否返回错误
              if(!data.success){
                 notifyShow('error', data.message);
                 fn(false);
                 return;
              }

              fn(true);

          },'json');




        }



    	//输入框类型编辑
    	$(document).on("click",".inputEdit",function(){

        //获取当前的数据源
        var idx = $("#tbodybox tr").index($(this).parent());

    		var title    = $(this).data("title");
    		var value    = $(this).prop("value");
        var detailId = $(this).parent().attr("id");
        var menuId   = $(this).parent().attr("name");
        var field    = $(this).data("field");

    		var d = dialog({
          width:500,
			    title  : title,
			    content: '<input class="form-control" id="inputEdit" value="'+value+'" />',
			    okValue: '修改',
			    ok: function () {

              //获取输入框内容
              var newValue = $("#inputEdit").val();

              //传递更新参数
              var params = {
                  id      : detailId,
                  menu_id : menuId,
                  field   : field,
                  value   : newValue
              };

              if(!isSubmit){
                return false;
              }

              isSubmit = false;
              this.title('正在处理...');

              //更新操作
              updateInterfactDetail(params,function(isSuccess){


                  if(isSuccess){
                    notifyShow('success', title + "更新成功");

                    //更新内容
                    $.observable(sonMenuListData.result[idx]).setProperty(field,newValue);
                  }
                  

                  //关闭
                  d.close().remove();
   
              });



			        return false;
			    },
			    cancelValue: '取消',
			    cancel: function () {}
			});
			d.showModal();
    	});


    	//单选框类型编辑
    	$(document).on("click",".radioEdit",function(){

    		//获取当前的数据源
        var idx = $("#tbodybox tr").index($(this).parent());

        var title    = $(this).data("title");
        var value    = $(this).prop("value");
        var detailId = $(this).parent().attr("id");
        var menuId   = $(this).parent().attr("name");
        var field    = $(this).data("field");

        var radioObj;
        if(value == 'POST'){
          radioObj = '<input type="radio" value="POST" checked name="requestType" />&nbsp;&nbsp;POST&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="GET" name="requestType" />&nbsp;&nbsp;GET';
        }else if(value == 'GET'){
          radioObj = '<input type="radio" value="POST" name="requestType" />&nbsp;&nbsp;POST&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="GET" checked name="requestType" />&nbsp;&nbsp;GET';
        }

    		var d = dialog({
			    title  : title,
			    content: radioObj,
			    okValue: '修改',
          ok :function(){

            var newValue = $("input[type='radio']:checked").val();

              //传递更新参数
              var params = {
                  id      : detailId,
                  menu_id : menuId,
                  field   : field,
                  value   : newValue
              };

            if(!isSubmit){
                return false;
              }

              isSubmit = false;
              this.title('正在处理...');

              //更新操作
              updateInterfactDetail(params,function(){

                  notifyShow('success', title + "更新成功");

                  //更新内容
                  $.observable(sonMenuListData.result[idx]).setProperty(field,newValue);

                  //关闭
                  d.close().remove();
   
              });



              return false;
          },
          cancelValue: '取消',
          cancel: function () {}
			  });
			  d.showModal();
    	});

    	//参数类型编辑
    	$(document).on("click",".paramsEdit",function(){

    		var title    = $(this).data("title");
        var detailId = $(this).parent().attr("id");
        var field    = $(this).data("field");

    		var d = dialog({
    			padding: 30,
			    title  : title,
			    okValue: '修改',
          onshow: function () {

             var params = {
                 id : detailId,
                 type : field
             }

             var that = this;
              
            //获取参数列表
            getParamsListData(params,function(data){

                if(data.length<=0){
                   that.content("该接口下未配置参数");
                   return false;
                }


                var listObj = "<ul class='paramsUl'>";
                for(var i=0;i<data.length;i++){

                  //拼接显示参数
                  var paramsStr = "";
                  paramsStr += data[i].is_must + "|" + data[i].params_name + "|" + data[i].params_type + "|" + data[i].params_description;

                  listObj += "<li id="+data[i].id+"><input type='text' class='form-control restfulParamsInput' value="+paramsStr+" placeholder='是否必须 ( YES/NO ) | 字段名 | 字段类型 ( String,Number,Array ) | 字段描述' /></div><span class='glyphicons glyphicons-bin removeParams'></span><span class='glyphicons glyphicons-list-alt editParams'></span></li>";

                }

                listObj += "</ul>";
                that.content(listObj);
                $(".paramsUl").mCustomScrollbar({theme:"rounded"});

                //删除该参数
                $(".removeParams").click(function(){

                    var paramsId = $(this).parent().attr("id");

                    //确认提示
                    var d = dialog({
                        title: '提示',
                        content: '您确定需要删除该参数吗？',
                        okValue : "确定",
                        ok : function(){

                          notifyShow('warning','暂不提供该功能');

                        },
                        cancelValue : "取消",
                        cancel:function(){}

                    });
                    d.showModal();
                });


                $(".editParams").click(function(){

                    var paramsId = $(this).parent().attr("id");

                    var paramsArr   = [$(this).parent().find("input").val()];

                    var paramsValue = verificationParams(paramsArr);

                    if(!paramsValue || paramsValue.length <= 0){
                       return false;
                    }

                    var params = {
                        id : paramsId,
                        paramsV : paramsValue[0]
                    };

                    $.post("./handler/updateParams.php",params,function(data){

                        //判断是否返回错误
                        if(!data.success){
                           notifyShow('error', data.message);
                           return;
                        }

                        notifyShow('success','参数更新成功');

                    },'json');


                });

                
            });
          }

			});
			d.showModal();
			
     
    	});

		//大输入框类型编辑
    	$(document).on("click",".resutlEdit",function(){

    		//获取当前的数据源
        var idx = $("#tbodybox tr").index($(this).parent());

        var title    = $(this).data("title");
        var value    = $(this).prop("value");
        var detailId = $(this).parent().attr("id");
        var menuId   = $(this).parent().attr("name");
        var field    = $(this).data("field");

    		var d = dialog({
			    title  : title,
			    content: '<textarea class="form-control" rows="20" cols="80" name="resultTextArea" >'+value+'</textarea>',
			    okValue: '修改',
			    ok: function () {

              var newValue = $("textarea[name='resultTextArea']").val();

              //传递更新参数
              var params = {
                  id      : detailId,
                  menu_id : menuId,
                  field   : field,
                  value   : newValue
              };

              if(!isSubmit){
                return false;
              }

              isSubmit = false;
              this.title('正在处理...');

              //更新操作
              updateInterfactDetail(params,function(){

                  notifyShow('success', title + "更新成功");

                  //更新内容
                  $.observable(sonMenuListData.result[idx]).setProperty(field,newValue);

                  //关闭
                  d.close().remove();
   
              });

			        return false;
			    },
			    cancelValue: '取消',
			    cancel: function () {}
			});
			d.showModal();
    	});

    	//权限编辑
    	$(document).on("click",".permissionEdit",function(){
    		var follow = $(this).find("span")[0];
      	var d = dialog({
  				align: 'bottom',
  				quickClose: true,
  				content: '暂未配置权限信息'
  			});
			  d.show(follow);
    	});

      //接口名称搜索
      $(document).on("click",".nameSearch",function(){
          var follow = $(this).find("span")[0];
          var d = dialog({
            align: 'right bottom',
            quickClose: true,
            content: '<input class="form-control" id="nameSearchInput" style="width:300px;" placeholder="请输入要搜索的接口名称" />',
          });
          d.show(follow);

          $("#nameSearchInput").keyup(function(){   

              var searchValue = $("#nameSearchInput").val();
              //接口内容过滤
              $("#tbodybox tr").hide().filter(":contains('"+searchValue+"')").show(); 

          });
      })

      //删除接口
      $(document).on("click",".removeInterface",function(){
           
          //确认提示
          var d = dialog({
              title: '提示',
              content: '您确定需要删除该参数吗？',
              okValue : "确定",
              ok : function(){

                notifyShow('warning','暂不提供该功能');

              },
              cancelValue : "取消",
              cancel:function(){}

          });
          d.showModal();

      });

      //获取参数列表
      function getParamsListData(params,fn){

          //加载根菜单
          $.getJSON("./handler/getParamsList.php",params,function(data){
              
              //判断是否返回错误
              if(!data.success){
                 notifyShow('error', data.message);
                 return;
              }

              fn(data.result);

          });


      }

    	//根菜单加载动画开始
    	function rootMenuLoadingStart(){
    		$(".rootMenuLoadingBox").show();
    	}

    	//根菜单加载动画结束
    	function rootMenuLoadingEnd(){
    		$(".rootMenuLoadingBox").hide();
    	}

    	//子接口列表开始
    	function sonMenuListLoadingStart(){
    		$("#loadingContent").show();
    	}

    	//子接口列表结束
    	function sonMenuListLoadingEnd(){
    		$("#loadingContent").hide();
    	}

    	//隐藏默认主菜单显示
    	function hideDefaultContent(){
    		$(".defaultContent").hide();
    	}

      //验证接口参数信息
      function verificationParams(v_paramsArr){

            //参数支持的数据类型
            var paramsType = ["String","Number","Array","File"];

            var restfulArr = [];
            for(var i=0;i<v_paramsArr.length;i++){

                  var paramsValue = v_paramsArr[i];

                  if(paramsValue.length>0){

                      //判断格式是否正确
                      var n = paramsValue.split('|').length-1;
                      if(n!=3){
                         notifyShow('warning', "（第"+(i+1)+"个）restful参数 - 数量不正确");
                         continue;  
                      }

                      //拆分参数
                      var paramsArr = paramsValue.split("|");

                      //拆分参数对象
                      var paramsRs = {};

                      //对每个参数进行验证 (参数一，是否必须传递)
                      paramsArr[0] = paramsArr[0].trim();
                      if(paramsArr[0] == ""){
                          notifyShow('warning', "（第"+(i+1)+"个）restful参数 - 请填写该参数是否必须传递");
                          continue;  
                      }else{
                          if(paramsArr[0] != "YES" && paramsArr[0] != "NO"){
                             notifyShow('warning', "（第"+(i+1)+"个）restful参数 - 是否需要进行传递参数填写错误（请填写YES/NO）");
                             continue;  
                          }
                      }
                      paramsRs.isMust = paramsArr[0];

                      //参数二，是否必须传递
                      paramsArr[1] = paramsArr[1].trim();
                      if(paramsArr[1]==""){
                          notifyShow('warning', "（第"+(i+1)+"个）restful参数 - 参数名不能为空");
                          continue;  
                      }
                      paramsRs.paramsName = paramsArr[1];

                      //参数三，字段类型
                      paramsArr[2] = paramsArr[2].trim();
                      if(paramsArr[2]==""){
                          notifyShow('warning', "（第"+(i+1)+"个）restful参数 - 参数类型不能为空");
                          continue;   
                      }else{

                          if(paramsType.indexOf(paramsArr[2]) == -1){
                             notifyShow('warning', "（第"+(i+1)+"个）restful参数 - 参数类型填写错误");
                             continue;  
                          }
                      }
                      paramsRs.paramsType = paramsArr[2];

                      //参数四，参数描述
                      paramsArr[3] = paramsArr[3].trim();
                      if(paramsArr[3]==""){
                          notifyShow('warning', "（第"+(i+1)+"个）restful参数 - 参数描述不能为空");
                          continue;  
                      }
                      paramsRs.paramsDesc = paramsArr[3];
                      restfulArr.push(paramsRs);

                 }else{
                    notifyShow('warning', "（第"+(i+1)+"个）restful参数内容不能为空");
                    return false;
                 }

            }

            return restfulArr;

      }
    });

    //去除两端空格
      String.prototype.trim = function(){
    　　    return this.replace(/(^\s*)|(\s*$)/g, "");
    　}

	</script>
</html>